package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile pic) throws IOException {
        //非空
        if (ObjectUtils.isEmpty(pic) || pic.isEmpty()){
            return ResultVO.failed("文件不能为空");
        }
        //类型判断
        if(!imageProperties.getTypes().contains(pic.getContentType())){
            String types = imageProperties.getTypes().stream().map(type -> type.substring(type.lastIndexOf("/") + 1)).collect(Collectors.joining("、"));
            return ResultVO.failed("仅仅支持"+types+"类型");
        }
        //创建文件名--- uuid.后缀名
        String fileName = IdUtil.simpleUUID()+"."+ FileNameUtil.getSuffix(pic.getOriginalFilename());
        //创建目录
        File uploadDir = new File(imageProperties.getUploadDir());
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        //目标文件 d:/upload/et2504/uuid.后缀名
        File destFile = new File(uploadDir,fileName);

        //上传
        pic.transferTo(destFile);

        //请求路径 /pics/uuid.后缀名
        String path = imageProperties.getMapping().endsWith("/")?
                imageProperties.getMapping()+fileName :
                imageProperties.getMapping()+"/"+fileName;
        return ResultVO.success(path);
    }

}
